// https://passer-by.com/data_location/list.json
const json = require('./list.json')

function buildNestedRegionTree(flatData) {
  const tree = []

  // 生成唯一的 ID（示例中使用编码作为 ID）
  function generateId(code) {
    return code // 这里直接用编码作为 ID
  }

  // 遍历平铺数据
  for (const code in flatData) {
    const name = flatData[code]
    const provinceCode = code.substring(0, 2) + '0000' // 省级编码
    const cityCode = code.substring(0, 4) + '00' // 市级编码
    const districtCode = code // 区级编码

    // 处理省级
    let provinceNode = tree.find(node => node.value === provinceCode)
    if (!provinceNode) {
      provinceNode = {
        id: generateId(provinceCode),
        label: flatData[provinceCode] || '未知省级',
        value: provinceCode,
        children: []
      }
      tree.push(provinceNode)
    }

    // 处理市级
    if (cityCode !== provinceCode) {
      let cityNode = provinceNode.children.find(node => node.value === cityCode)
      if (!cityNode) {
        // 县级市下面没有行政区了
        if (!flatData[cityCode]) {
          cityNode = provinceNode
        } else {
          cityNode = {
            id: generateId(cityCode),
            label: flatData[cityCode] || '未知市级',
            value: cityCode,
            children: []
          }
          provinceNode.children.push(cityNode)
        }
      }

      // 处理区级
      if (districtCode !== cityCode) {
        const districtNode = {
          id: generateId(districtCode),
          label: name,
          value: districtCode
          // children: [], // 区级没有子节点
        }
        cityNode.children.push(districtNode)
      }
    }
  }

  return tree
}

// 示例数据
// const flatData = {
//   "820000": "澳门特别行政区",
//   "820100": "澳门半岛",
//   "820101": "花地玛堂区",
//   "820102": "圣安多尼堂区",
//   "820103": "大堂区",
//   "820104": "望德堂区",
//   "820105": "风顺堂区",
//   "820200": "离岛",
//   "820201": "嘉模堂区",
//   "820202": "圣方济各堂区",
//   "820203": "路氹城",
//   "820204": "澳门新城",
// };

// 转换为嵌套结构
// const nestedTree = buildNestedRegionTree(flatData);
// console.log(JSON.stringify(nestedTree, null, 2));

const options = buildNestedRegionTree(json)
